import React, { useEffect, useRef, useState } from 'react'
import { Input, Button, message, List, Typography, Avatar, Skeleton } from 'antd'
import { postAIChat } from '@/util/request'
import { useAppSelector } from '@/store'
import { select_user_info } from '@/store/slice/user/select'
import { imgUrl } from '@/util/constant'
import deepseek_logo from './static/deepseek.png'
import styles from './index.module.scss'

export default function AIChat() {
  // 用于存储对话消息的状态
  const [messages, setMessages] = useState<any>([])
  // 用于存储输入框内容的状态
  const [inputValue, setInputValue] = useState('')

  // const [loading, setLoading] = useState(false)

  const [messageApi, contextHolder] = message.useMessage()

  const userinfo = useAppSelector(select_user_info)

  // 发送消息的函数
  const handleSendMessage = async () => {
    if (inputValue.trim() === '') {
      messageApi.open({
        type: 'warning',
        content: '请输入内容'
      })
      return
    }

    // 创建新的用户消息对象
    const newUserMessage = { text: inputValue, sender: 'user', loading: false }
    // 更新消息列表，添加用户消息
    setMessages([...messages, newUserMessage])

    // 清空输入框
    setInputValue('')

    // setLoading(true)
    // 向deepseek发送对话内容
    const res: any = await postAIChat({
      content: inputValue
    })

    if (res.data.code == 200) {
      const deepseekMessage = { text: res.data.data, sender: 'deepseek', loading: false }
      setMessages([...messages, newUserMessage, deepseekMessage])
      // setLoading(false)
    }
  }

  return (
    <>
      {contextHolder}
      <div className={styles.container}>
        {/* 消息展示区域 */}
        <List
          // loading={loading}
          style={{ padding: 20, height: '100%' }}
          bordered
          dataSource={messages}
          renderItem={(message: any, index) => (
            // <List.Item key={index}>
            //   <Typography.Text mark style={{ textAlign: message.sender === 'user' ? 'right' : 'left' }}>
            //     {message.text}
            //   </Typography.Text>
            // </List.Item>
            <List.Item.Meta style={{ textAlign: message.sender === 'user' ? 'right' : 'left' }} key={index} avatar={<Avatar src={message.sender === 'user' ? imgUrl + userinfo.avatar : deepseek_logo} />} title={message.text}>
              {/* <Typography.Text mark style={{ textAlign: message.sender === 'user' ? 'right' : 'left' }}>
                {message.text}
              </Typography.Text> */}
            </List.Item.Meta>
          )}
        />
      </div>
      <div className={styles.send}>
        {/* 输入框和发送按钮 */}
        <Input onPressEnter={handleSendMessage} value={inputValue} onChange={e => setInputValue(e.target.value)} placeholder="请输入消息" style={{ width: '80%', marginRight: 10 }} />
        <Button onClick={handleSendMessage} type="primary">
          发送
        </Button>
      </div>
    </>
  )
}
